//
// Created by chizuru on 2025/9/2.
//

#include "PxdSerialAdapter.h"
#include <windows.h>
#include "xcliball.h"

PxdSerialAdapter::PxdSerialAdapter(int unit): unit(unit) {}

int PxdSerialAdapter::configure( std::any baud, std::any dataBits, std::any parity, std::any stopBits, std::any flowctrl) {
    int  _baud;
    int _dataBits;
    int _parity;
    int _stopBits;
    try {
        _baud = std::any_cast<int>(baud);
        _dataBits = std::any_cast<int>(dataBits);
        _parity = std::any_cast<int>(parity);
        _stopBits = std::any_cast<int>(stopBits);
    }catch (...) { return 0; }

    int ret = pxd_serialConfigure(unit, 0, _baud, _dataBits, _parity, _stopBits, 0, 0, 0);
    if  (ret < 0) {
        std::cerr << pxd_mesgErrorCode(ret) << std::endl;
        return ret;
    }
    return 0;
}

int PxdSerialAdapter::write( const char* data, size_t size)  {
    // 创建非 const 副本（最安全但性能稍差）
    std::vector<char> buffer(data, data + size);

    int int_size = static_cast<int>(size);
    int ret = pxd_serialWrite(unit, 0, buffer.data(), int_size);

    if (ret < 0) {
        std::cerr << pxd_mesgErrorCode(ret) << std::endl;
    }

    return ret;
}

int PxdSerialAdapter::read( char* buf, size_t maxSize)  {
    int ret = pxd_serialRead(unit, 0, buf, maxSize - 1);/* 避免缓冲区溢出 */
    if(ret < 0){
        std::cerr << pxd_mesgErrorCode(ret) << std::endl;
    }
    return ret;
}

int PxdSerialAdapter::flushReadAndWrite() {
    auto r = pxd_serialFlush(unit, 0, 1, 1);
    if (r < 0){
        std::cerr << pxd_mesgErrorCode(r) << std::endl;
    }

    return 0;
}
